/**
 * 
 */
package com.wsd.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.List;
import java.util.Set;


import com.wsd.bean.Message;
import com.wsd.bean.OrderList;
import com.wsd.bean.Price;
import com.wsd.bean.ProductOrder;
import com.wsd.bean.Products;
import com.wsd.bean.Users;
import com.wsd.dao.MessageDaoInterface;
import com.wsd.dao.OrderListDaoInterface;
import com.wsd.dao.ProductOrderDaoInterface;
import com.wsd.dao.ProductsDaoInterface;
import com.wsd.dao.UsersDaoInterface;
import com.wsd.service.UserService;

/**
 * @author TuZiJun
 *
 */
public class UserServiceImpl implements UserService {
	private UsersDaoInterface usersDAO = null;
	private MessageDaoInterface messageDAO = null;
	private ProductsDaoInterface productsDAO = null;
	private ProductOrderDaoInterface productOrderDAO = null;
	private OrderListDaoInterface orderListDAO = null;
	public void setOrderListDAO(OrderListDaoInterface orderListDAO) {
		this.orderListDAO = orderListDAO;
	}
	public void setProductsDAO(ProductsDaoInterface productsDAO) {
		this.productsDAO = productsDAO;
	}
	public void setProductOrderDAO(ProductOrderDaoInterface productOrderDAO) {
		this.productOrderDAO = productOrderDAO;
	}
	public void setMessageDAO(MessageDaoInterface messageDAO) {
		this.messageDAO = messageDAO;
	}
	public void setUsersDAO(UsersDaoInterface usersDAO) {
		this.usersDAO = usersDAO;
	}
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#login()
	 */
	public Users login(Users user) {
		List<Users> users = usersDAO.findByExample(user);
		return users.size() == 0 ? null : users.get(0);
	}
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#showMessage(int, int)
	 */
	public List<Message> showMessage(int page, int pagesize) {
		int start = (page - 1) * pagesize;
		return messageDAO.findOnePage(start, pagesize);
	}
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#getMessagePage(int)
	 */
	public int getMessagePage(int pagesize) {
		int totalPage = ((Long) messageDAO.getTotallines().get(0)).intValue();
		totalPage = totalPage % pagesize == 0 ? totalPage / pagesize : totalPage / pagesize + 1;
		return totalPage;
	}
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#liveMessage(com.wsd.bean.Message)
	 */
	public boolean saveMessage(Message message) {
		boolean result = false;
		try {
			message.setMTime(new Timestamp(System.currentTimeMillis()));
			messageDAO.save(message);
			result = true;
		} catch (Exception e) {
			return result;
		}
		return result;
	}
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#checkUserName(java.lang.String)
	 */
	public boolean checkUserName(String username) {
		return usersDAO.findByUsername(username).size() > 0;
	}
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#findByExample(com.wsd.bean.Users)
	 */
	public List<Users> findByExample(Users user,int start,int limit) {
		return usersDAO.findByExample(user,start,limit);
	}
	public List<Users> findUsers(String[] names, Object[] values, int start, int limit) {
		return usersDAO.findUsers(names,values,start,limit);
	}
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#findByExampleCount(java.lang.String[], java.lang.Object[])
	 */
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#findUsersCount(java.lang.String[], java.lang.Object[])
	 */
	public int findUsersCount(String[] names, Object[] values) {
		return usersDAO.findUsersCount(names,values);
	}
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#searchUsers(java.lang.String, java.lang.String[], java.lang.Object[], int, int)
	 */
	public List<Users> searchUsers(String key, String[] names, Object[] values, int start, int limit) {
		return usersDAO.searchUsers(key,names,values,start,limit);
	}
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#searchUsersCount(java.lang.String, java.lang.String[], java.lang.Object[])
	 */
	public int searchUsersCount(String key, String[] names, Object[] values) {
		return usersDAO.searchUsersCount(key,names,values);
	}
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#updateState(int[], boolean)
	 */
	public void updateState(int[] userIds, boolean state) {
		for(int userId : userIds){
			usersDAO.updateState(userId,state);
		}
	}
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#updateLevel(int[], int)
	 */
	public void updateLevel(int[] userIds, int userLevel) {
		for(int userId : userIds){
			usersDAO.updateLevel(userId,userLevel);
		}
	}
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#updateUser(com.wsd.bean.Users)
	 */
	public void updateUser(Users user) {
		usersDAO.update(user);
	}
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#findById(java.lang.Integer)
	 */
	public Users findById(Integer userid) {
		return usersDAO.findById(userid);
	}
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#addProduct(java.util.Set, int)
	 */
	@SuppressWarnings("unchecked")
	public Set<OrderList> saveProduct(Set<OrderList> orderlist,int pnum, int pid, int userLevel) {
		boolean ishas = false;
		OrderList ol = new OrderList();
		float productPrice = 0.0f;
		for (OrderList order : orderlist) {
			if(pid == order.getProducts().getPId()) {
				ishas = true;
				ol = order;
				pnum += order.getLNum();
				orderlist.remove(order);
				break;
			}
		}
		if (!ishas) {
			Products product = productsDAO.findById(pid);
			ol.setProducts(product);
			Set<Price> prices = product.getPrices();
			for(Price price : prices) {
				if(userLevel == price.getULevel()) {
					productPrice = price.getPrice();
					ol.setLPrice(productPrice);
					break;
				}
			}
		}
		ol.setLNum(pnum);
		ol.setLSumPrice(ol.getLPrice() * ol.getLNum());
		orderlist.add(ol);
		return orderlist;
	}
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#deleteProduct(java.util.Set, int)
	 */
	public Set<OrderList> deleteProduct(Set<OrderList> orderlist, int pid) {
		for (OrderList order : orderlist) {
			if(pid == order.getProducts().getPId()) {
				orderlist.remove(order);
				break;
			}
		}
		return orderlist;
	}
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#saveProductOrder(java.util.Set, com.wsd.bean.Users)
	 */
	public ProductOrder saveProductOrder(Set<OrderList> orderlist, Users user) {
		int sum = 0;
		float sumPrice = 0.0f;
		ProductOrder po = new ProductOrder();
		for (OrderList order : orderlist) {
			sum += order.getLNum();
			sumPrice += order.getLSumPrice();
		}
		po.setOTime(new Timestamp(System.currentTimeMillis()));
		po.setOState(false);
		po.setOSumNum(sum);
		po.setOSumPrice(sumPrice);
		po.setUsers(user);
		productOrderDAO.save(po);
		for (OrderList order : orderlist) {
			order.setProductOrder(po);
			orderListDAO.save(order);
		}
		return po;
	}
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#saveUser(com.wsd.bean.Users)
	 */
	public boolean saveUser(Users user) {
		boolean result = false;
		try {
			user.setState(false);
			user.setUserLevel(1);
			user.setRegisterTime(new Timestamp(System.currentTimeMillis()));
			usersDAO.save(user);
			result = true;
		} catch (Exception e) {
			return result;
		}
		return result;
	}
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#showOrder()
	 */
	public List<ProductOrder> showOrder(Integer uid) {
		return productOrderDAO.findByStateUid(uid);
	}
	/* (non-Javadoc)
	 * @see com.wsd.service.UserService#checkName(com.wsd.bean.Users)
	 */
	public boolean checkName(Users user) {
		try {
			user.setUsername(URLDecoder.decode(user.getUsername(),"utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		List<Users> users = usersDAO.findByExample(user);
		return users.size() == 0 ? false : true;
	}

}
